Ext.namespace('VAS');
VAS.CompositeSelect = Ext.extend(Ext.form.CompositeField, {
	initComponent : function() {
		var _this = this;
		var _displayField = this.name + "_" + _this.displayField;
		var textfieldWidth = _this.width != 0 ? _this.width : '80%' ;
		var config = {
			combineErrors: false,
			items : [{
						xtype : 'textfield'
						,name : _displayField
						,readOnly : true
						,width : textfieldWidth
						,allowBlank : _this.allowBlank
						,blankText  : _this.blankText
					}, {
						xtype : 'button',
						iconCls : 'icon_search',
						handler : function() {
							Ext.Ajax.request({
								url : _this.url,
								method : "POST",
								success : function(response) {
									//检查session是否过期
									checkTimeOut(response);
									var responseObj = Ext.util.JSON.decode(response.responseText);
									if (responseObj.success) {
										var win = new VAS.CommQueryGridWin({
											popUp : {
												id              : "compositeselectWin",
												compositeSelect : _this,
												fromForm        : true,
												wins            : responseObj.wins
											}
										});
										win.show();
									} else {
										alertFailure(responseObj);
									}
								},
								failure : function(response) {
									Ext.Msg.alert('提示', '服务器异常！');
								}
							});
						}
					}, {
						xtype : 'textfield',
						hidden : true,
						id : _this.id,
						name : _this.name,
						hiddenLabel : true
					}]

		};
		Ext.apply(this, config);
		Ext.apply(this.initialConfig, config);
		VAS.CompositeSelect.superclass.initComponent.apply(this, arguments);
	},
	
	setFilePathValue : function(record) {
		var _this = this;
		var filePath = this.items.itemAt(0);
		eval(_this.evalString)	//执行后台返回的js代码，执行一些自定义的操作
		filePath.setValue(record.get(this.displayField));
		var hiddenField = Ext.getCmp(_this.id);// 要回传到server的videoID
		hiddenField.setValue(record.get(this.valueField));
	}
});

Ext.reg('compositeSelect', VAS.CompositeSelect);

VAS.CommQueryGridWin = function($config) {
	var _this = this;
	var wins = $config.popUp.wins[0];
	var _queryPanel = null;
	var _grid = null;
	var _dynamicFormPanel = null;
	_this.items = [];

	
	// queryPanel
	if (typeof(wins.formPanel) == 'object') {
		var height = 0;
		if( typeof(wins.formPanel.height) == 'number' && wins.formPanel.height > 0){
			height = wins.formPanel.height;
		}else{
			height = 70;
		}
		var queryPanelUrl = wins.formPanel.url;
		var queryPanelId = wins.formPanel.id;
		var queryPanel = new VAS.DynamicItems({
			title : '查询条件',
			url : queryPanelUrl,
			id : queryPanelId,
			border : false,
			height : height,
			width : '100%',
			style : "margin-bottom: 5px"
			,gridId: wins.gridPanel.id
		});
		_queryPanel = queryPanel;
		_this.items.push(_queryPanel);
	}

	
	
	
	// gridPanel
	if (typeof(wins.gridPanel) == 'object') {
		
		var gridId = "";
		getParams = function(record) {
			var _params = '';
			var fieldName;
			var value;
			var cm = $config.popUp.grid.getColumnModel();
			for (var i = 0; i < cm.getColumnCount(); i++) {
				fieldName = cm.getDataIndex(i);
				value = record.get(fieldName);
				if (fieldName != '') {
					_params = (_params === null || _params == '') ? 
							+ fieldName + "=" + value : _params + "&"
							+ fieldName + "=" + value;
				}
			}

			return _params;

		}
		
		var params = typeof($config.popUp.record) === 'undefined' ? '' : getParams($config.popUp.record);
		
		if (typeof(wins.gridPanel.params) != 'undefined') {
			var par = wins.gridPanel.params;
			if (typeof(wins.gridPanel.params) == "string") {
				par = Ext.util.JSON.decode(wins.gridPanel.params);
			}
	    	var postParams = "";
	    	for(var p in par) {
	    		if(postParams != "") {
	    			postParams += "&";
	    		}
	    		postParams += p +"="+ Ext.util.JSON.encode(par[p]);
	    		
	    	}			
			if(params != "") {
				params += "&"+postParams;
			} else {
				params  = postParams;
			}
		}
		
		
		var gridId = wins.gridPanel.id;
		var gridUrl = wins.gridPanel.url
		var gridStoreUrl = wins.gridPanel.storeUrl;
		if (gridUrl.lastIndexOf("?") == -1) {
			gridUrl += "?"+params
		} else {
			gridUrl += "&"+params
		}
		if (gridStoreUrl.lastIndexOf("?") == -1) {
			gridStoreUrl += "?"+params
		} else {
			gridStoreUrl += "&"+params
		}
		
		var sm;
		if ($config.popUp.compositeSelect != undefined) {
			sm = new Ext.grid.RowSelectionModel({
				defaults : {
					sortable : true
				}
			})	
		} else {
			sm = new Ext.grid.CheckboxSelectionModel({
				defaults : {
					sortable : true											
				}
			})
		}
		//如果有 快速新增修改panel 则高度设置为250，没有则设置为300
		var gridHeight ;
		if( typeof(wins.gridPanel.height) == 'number' && wins.formPanel.height > 0){
			gridHeight = wins.formPanel.height;
		}else{
			if(typeof(wins.operatePanel) == 'object'){
				gridHeight = 250;
			}else{
				gridHeight = 340;
			}
		}
		
		var grid = new VAS.CellEditorGrid({
			title : "数据列表",
			id : gridId,
			gridUrl : gridUrl,
			storeUrl : gridStoreUrl,
			rowNumberer : true,
			border : true,
			draggable : true,
			checkboxSelModel : true,
			params : wins.gridPanel.params,
			sm : sm,
			height : gridHeight,
			autoScroll : true,
			autoWidth : true,
			page : true,
			lisenters : {},
			popUp : $config.popUp,
			storeId : 'popUp_grid_store_'+gridId,
			pageSize : 10
		});
		_grid = grid;
		_this.items.push(_grid);
	}

	// 选择的确定按钮，跟双击表格功能相同
	// _this.items.push(confirmButton);
	// _this.items.push(closeButton);

	

		
	// 快速新增修改
	if (typeof(wins.operatePanel) == 'object') {
		_this.saveBt = {
			text : '清空',
			handler : function() {
				_this.dynamicFormPanel.getForm().reset();
			}
		};

		_this.addBt = {
			text : '保存',
			handler : function() {
				if (_this.dynamicFormPanel.getForm().isValid()) {
					_this.dynamicFormPanel.getForm().submit({
						url : _this.action,
						waitTitle : '正在提交',
						waitMsg : '正在向服务器发送请求',
						clientValidation : true,
						params : {
							formPanelId : wins.operatePanel.id
						},
						success : function(form, action) {
							Ext.Msg.alert('提示', '提交保存成功!', function() {
								_this.dynamicFormPanel.getForm().reset();
								grid.store.reload();
							});
						},
						failure : function(form, action) {
							if (action.failureType == Ext.form.Action.CLIENT_INVALID) {
								Ext.Msg.alert('提示', '输入的信息不符合规格，请按照提示重新输入！');
							} else {
								alertFailure(action.result);
							}
						}
					});
				} else {
					Ext.Msg.alert('提示', '请填入必填项');
				}
			}
		};
		
		var operaterPanelUrl = wins.operatePanel.url;
		_this.action = wins.operatePanel.action;
		var _data = SyncAjax(operaterPanelUrl);
		_this.dynamicFormPanel = new VAS.DynamicEditForm({
				id : 'commQueryWin_formPanel',
				title : "快速新增修改",
				minButtonWidth  : 50,
				fieldSet : _data.fieldSet,
//				style : "margin-top: 5px",
				buttons : [_this.addBt, _this.saveBt]
			});
			_this.dynamicFormPanel.hidden = true;
		_dynamicFormPanel = _this.dynamicFormPanel;
		_this.items.push(_dynamicFormPanel);
	};
	
	
	
	if ($config.popUp.compositeSelect != undefined) {
		var confirmButton = new Ext.Button({
			id : 'confirm',
			text : '确定',
			handler : function() {
				var selected = grid.getSelectionModel().getSelected();
				if (selected == undefined) {
					Ext.Msg.alert('提示', '请选择');
					return false;
				}
				_this.popUp.compositeSelect.setFilePathValue(selected);
				_this.close();
			}
		});
	} else if($config.popUp.event != undefined && wins.gridPanel.compositeSelect == undefined){
			var saveBt = new Ext.Button({
				id : 'saveBt',
				text : '提交',
				handler : function() {
	    		 	var _records = grid.getSelectionModel().getSelections();   	
	    		 	if (typeof(_records)==='undefined'||_records.length==0) {
	    		 		Ext.Msg.alert('提示','您没有选择数据');
	    		 		return;
	    		 	}
	    		 	var _postData    = {};
	    			_postData.items  = [];
	    			for (var i=0;i<_records.length;i++) {
	    				var  _record;
	    				_record=_records[i];		 
	    				_postData.items.push(_record.data);				
	    			}  		
	    	    	var par = wins.gridPanel.params;
					if (typeof(wins.gridPanel.params) == "string") {
						par = Ext.util.JSON.decode(wins.gridPanel.params);
					}
	    	    	var postParams  = {};
	    	    	for(var p in par) {
	    	    		postParams[p] = Ext.util.JSON.encode(par[p]);
	    	    	}	    			
				    Ext.Ajax.request({
					   url    : wins.gridPanel.action,
					   method : "POST",
					   params : Ext.apply({data:Ext.util.JSON.encode(_postData)},postParams),				   
					   success: function(response) {
					   	   //检查session是否过期
						   checkTimeOut(response);
    					   var responseObj = Ext.util.JSON.decode(response.responseText);
    					   if (responseObj.success) {
								$config.popUp.event.store.reload();
								_this.close();
    					   } else {
    					   		alertFailure(responseObj);
    					   }					   	
					   }, failure: function(response) {
							Ext.Msg.alert('提示','服务器异常！');
					   }
				   });	    			
				}
			});
	}else if($config.popUp.id == "transferWin"){
			var transferBt = new Ext.Button({
				id : 'transferBt',
				text : '转移',
				handler : function() {
	    		 	var _records = grid.getSelectionModel().getSelections();   	
	    		 	if (typeof(_records)==='undefined'||_records.length==0) {
	    		 		Ext.Msg.alert('提示','您没有选择数据');
	    		 		return;
	    		 	}
					if (_records.length>1) {
	    		 		Ext.Msg.alert('提示','请选择一条记录');
	    		 		return;
	    		 	}
	    		 	var _postData    = {};
	    			_postData.items  = [];
	    			for (var i=0;i<_records.length;i++) {
	    				var  _record;
	    				_record=_records[i];		 
	    				_postData.items.push(_record.data);				
	    			}
					var par = wins.gridPanel.params;
					if (typeof(wins.gridPanel.params) == "string") {
						par = Ext.util.JSON.decode(wins.gridPanel.params);
					}
	    	    	var postParams  = {};
	    	    	for(var p in par) {
	    	    		postParams[p] = Ext.util.JSON.encode(par[p]);
	    	    	}
				    Ext.Ajax.request({
					   url    : wins.gridPanel.action,
					   method : "POST",
					   params : Ext.apply({data:Ext.util.JSON.encode(_postData)},postParams),				   
					   success: function(response) {
					   	   //检查session是否过期
						   checkTimeOut(response);
    					   var responseObj = Ext.util.JSON.decode(response.responseText);
    					   if (responseObj.success) {
								$config.popUp.grid.store.reload();
								_this.close();
    					   } else {
    					   		alertFailure(responseObj);
    					   }					   	
					   }, failure: function(response) {
							Ext.Msg.alert('提示','服务器异常！');
					   }
				   });	    			
				}
			});
	}
	
	_this.cancleBt = {
		text : '关闭',
		handler : function() {
			_this.close();
			$config.popUp.grid.store.reload();
		}
	};
	
	//设置窗口的默认宽度为80%。
	//初始化页面的sql中大部分的width都为'100%'，所以把'100%'视为对宽度不做限制，取默认值'80%'。
	if(wins.width == '100%'){
		wins.width = '80%';
	}
	var thisConfig = {
		//id : 'CommQueryGridWin',
		id    : $config.popUp.id,
		items : _this.items,
		width : wins.width,
//		height: wins.height,
		modal : true,
		listeners     : {
				beforedestroy : function() {
					var gridStore = Ext.StoreMgr.lookup('popUp_grid_store_'+wins.gridPanel.id);
					if (typeof gridStore != "undefined") {
						Ext.StoreMgr.unregister("popUp_grid_store_"+wins.gridPanel.id);  
					}
				}
		}		
	
	};
	// 如果是compositeSelect， 则加上确定和关闭按钮
	if (typeof(wins.operatePanel) != 'object') {
		if($config.popUp.compositeSelect != undefined) {
			Ext.apply(thisConfig, {
				buttons : [confirmButton, _this.cancleBt]
			})
		}
	} 
	//如果不是compositeSelect，就加上提交、关闭按钮
	if($config.popUp.event != undefined && wins.gridPanel.compositeSelect == undefined  ) {
		Ext.apply(thisConfig, {
			buttons : [saveBt,_this.cancleBt]
		})
	}
	//如果是一对多，则加上关闭按钮
	if($config.popUp.id == "childmanageWin"){
		Ext.apply(thisConfig, {
			buttons : [_this.cancleBt]
		})
	}
	//如果是批量转移文章按钮，则加上转移按钮 关闭按钮
	if ($config.popUp.id == "transferWin") {
		Ext.apply(thisConfig, {
			buttons : [transferBt,_this.cancleBt]
		})
	}
	var _config = $config || {};

	Ext.apply(_this, Ext.apply(thisConfig, _config));
	VAS.CommQueryGridWin.superclass.constructor.call(_this);

};

Ext.extend(VAS.CommQueryGridWin, Ext.Window, {
manager:wgroup});
